<template>
    <div class="pagePad">
        <!-- 页面内容 -->
        <div class="content">
            <!-- 页面头部 -->
            <div class="contentTop">
                <!-- 条件输入 -->
                <div class="input">
                    <!-- 搜索框 -->
                    <van-search class="searchView" placeholder="请输入客户姓名" v-model="customName" :show-action="showAction" reverse-color
                        @search="onSearch" @cancel="onCancel" @focus="onFocus" />
                        <div class='searchButton' @click="onSearch">搜索</div>
                    <!-- 下拉选择框 -->
                    <van-dropdown-menu class="dropdownMenu">
                        <van-dropdown-item v-model="dateInterval" :options="dropdownMenuList" @change="onSearch" />
                    </van-dropdown-menu>
                </div>
                <div  v-if="type == '1'" style="margin:12px 0 0 0 ;float:right;">
                        <van-radio-group v-model="strore.checkedId" direction="horizontal" size="small" @change="strore.filterCompletedData()">
                            <van-radio name="2">全部授权</van-radio>
                            <van-radio name="1">已授权</van-radio>
                            <van-radio name="0">未授权</van-radio>
                        </van-radio-group>
                    </div>
            </div>

            <!-- 列表页 -->
            <div class="listView">
                
                <van-list v-if="type == '1'" class="vanList" v-model:loading="loading" :finished="finished"
                    finished-text="没有更多了" @load="getList">
                    <!-- <van-cell class="cells" v-for="(item,index) in listDataCompleted" :key="index"> -->
                    <van-cell class="cells" v-for="(item,index) in strore.fillCompletedStatuslist" :key="index">
                        <div class="card">
                            <div class="cardLine"> </div>
                            <div class="cardTT">
                                <div class="labels firstdiv">
                                    <div class="fontone">
                                        授权状态:</div>
                                        <span class="textContent" > {{authFlagFromat(item)  }}</span>
                                    </div>
                                <div class="labels">
                                    <div>客户姓名:</div>
                                    <span class="textContent">{{ item.monManName || '' }}</span>
                                </div>
                                <div class="labels">
                                    <div>邀请时间:</div>
                                    <span class="textContent">{{ item.createTime || '' }}</span>
                                </div>
                                <div class="labels">
                                    <div>任务编号:</div>
                                    <span class="textContent">{{item.taskCode|| '' }}</span>
                                </div>
                                <div class="labels">
                                    <div>任务备注:</div>
                                    <!-- <input disabled class="labelsInput" v-model="item.remark" maxlength="20" type="text" placeholder=""> -->
                                    <span class="textContent">{{item?.remark }}</span>
                                </div>
                                <div class="labels labelsButt">
                                    <!-- <span class="labelsButton" @click.stop="detAgainClick(item)">删除</span> -->
                                    <span class="labelsButton" @click.stop="getUpdateTaskRemark(item,index)" v-log-button-name="'保单检视_已完成任务_编辑备注'">编辑备注</span>
                                    <span class="labelsButton" @click.stop="inviteAgainClick(item)" v-log-button-name="'保单检视_已完成任务_再次邀请'">再次邀请</span>
                                </div>
                            </div>
                            <div style="position: relative;margin-left: 2%;" @click="golistReports(item)" v-log-button-name="'保单检视_已完成任务_查看报告'">
                                <van-image style="position: absolute; top: 50%; transform: translateY(-50%);" width="30"
                                    height="30" :src="goRightdetailedVersion" />
                            </div>
                        </div>
                    </van-cell>
                </van-list>

                <van-list v-if="type == '2'" class="vanList" v-model:loading="loading" :finished="finished"
                    finished-text="没有更多了" @load="getList">
                    <van-cell class="cells" v-for="(item,index) in listDataCompleted" :key="index">
                        <div class="card">
                            <div class="cardLine"> </div>
                            <div class="cardTTwo">
                                <div class="labels firstdiv">
                                    <div class="fontone">
                                        任务状态:</div>
                                    <span class="textContent">{{taskStatusFromat(item.taskStatus) || ''  }}</span>
                                </div>
                                <div class="labels">
                                        <div>客户姓名:</div>
                                        <span class="textContent">{{ item.monManName || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>邀请时间:</div>
                                        <span class="textContent">{{ item.createTime || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>任务编号:</div>
                                        <span class="textContent">{{item.taskCode  || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>任务备注:</div>
                                        <!-- <input disabled class="labelsInput" v-model="item.remark" maxlength="20" type="text" placeholder=""> -->
                                        <span class="textContent">{{item?.remark }}</span>
                                </div>
                                    <div class="labels labelsButt" >
                                        <span class="labelsButton" @click.stop="getUpdateTaskRemark(item,index)">编辑备注</span>
                                        <span class="labelsButton" @click.stop="inviteAgainClick(item)">再次邀请</span>
                                    </div>
                            </div>
                            <div @click.stop="goinviteCode(item)" >
                                <van-image style="position: absolute; top: 5%; right: 1.7%;" width="22" height="22" v-log-button-name="'保单检视_进行中任务_邀请二维码'"
                                    :src="cod" />
                            </div>
                        </div>
                    </van-cell>
                </van-list>

                <van-list v-if=" type == '3'" class="vanList" v-model:loading="loading" :finished="finished"
                    finished-text="没有更多了" @load="getList">
                    <van-cell class="cells" v-for="(item,index) in listDataCompleted" :key="index">
                        <div class="card">
                            <div class="cardLine"> </div>
                            <div class="cardTTwo">
                                <div class="labels firstdiv">
                                    <div class="fontone">
                                        任务状态:</div>
                                    <span class="textContent">{{taskStatusFromat(item.taskStatus) || ''  }}</span>
                                </div>
                                <div class="labels">
                                        <div>客户姓名:</div>
                                        <span class="textContent">{{ item.monManName || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>邀请时间:</div>
                                        <span class="textContent">{{ item.createTime || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>任务编号:</div>
                                        <span class="textContent">{{item.taskCode || ''  }}</span>
                                    </div>
                                    <div class="labels">
                                        <div>任务备注:</div>
                                        <!-- <input disabled class="labelsInput" v-model="item.remark" maxlength="20" type="text" placeholder=""> -->
                                        <span class="textContent">{{item?.remark }}</span>
                                    </div>
                                    <div class="labels labelsButt" >
                                        <!-- <span class="labelsButton" @click.stop="detAgainClick(index)">删除</span> -->
                                        <span class="labelsButton" @click.stop="getUpdateTaskRemark(item,index)">编辑备注</span>
                                        <span class="labelsButton" @click.stop="inviteAgainClick(item)">再次邀请</span>
                                    </div>
                            </div>
                        </div>
                    </van-cell>
                </van-list>
          </div>
        </div>
        <van-overlay :show="show">
            <div class="wrapper">
                <div class='wrapperChild'>
                    <div class='wrapperChildDiv'>
                                                <!-- <input class="labelsInput" v-model="remarkInputValue"  maxlength="20" type="text" placeholder="您可以在此处输入备注信息">-->
                                                <textarea v-model="remarkInputValue" maxlength="80" placeholder="您可以在此处输入备注信息"  rows="3"></textarea>
                        <div class='wrapperChildBottom'>
                            <div @click="wrapperUpdateTaskRemarkqx()">取消</div>
                            <div @click="wrapperUpdateTaskRemark()">确定</div>
                        </div>
                    </div>
                </div>
            </div>
        </van-overlay>
    </div>
</template>

<script lang="ts" setup name="Task">
import { showDialog } from 'vant'
import { Toast } from '/@/utils/Message';
import { onBeforeUnmount, onMounted } from "vue"
import { ref, reactive, watchEffect,watch} from 'vue'
import { dropdownMenuList, listDataCompleted, ListFormdata } from '../Task/ts/task'
import {  taskInfo} from "/@/api/auth/task"
import { taskStatusFromat,authFlagFromat} from '/@/utils/taskFormat'
import { useRouter, useRoute } from "vue-router"
import { selMyTaskDetail, updateTaskRemark, deleteTask } from "/@/api/auth/task"
import { sm2 } from 'sm-crypto';
import cod from "../../assets/img/features/cod.png"
import goRightdetailedVersion from "../../assets/img/features/rightRound.png"
import {workbenchesStrore} from "/@/stores/workbenchesStore"

const strore = workbenchesStrore()
//公钥串---加密使用
const publicKey = ref<string>("044291b381a039a8d7d02d7272d2d7c78a30d33e3eeaa0b509bf77d2376582ab2d573730e6bfe9a53bad53f53ac1a85d9c11050931f04bc8b3afc04144d5a6f9be")
//私钥串---解密使用
const privateKey = ref<string>("5aa03412c3051e1d4cf9d19cfbeeec70c28f388c9f82747cc912096c9cd44bea")
// 加密方法
const JIAMIPublicData=(data:any):string=> {
    const cipherMode = 1;
    const result = sm2.doEncrypt(data, publicKey.value,cipherMode);
    return `04${result}`;
}
// 解密方法
const JIMIPublicData=(data:any):string=> {
    const cipherMode = 1;
    //data为加密的数据
    const result = sm2.doDecrypt(data.substring(2), privateKey.value,cipherMode)
    return result;
}

const router = useRouter()
const route = useRoute()
const show = ref<boolean>(false)
const showAction = ref<boolean>(false)
let arrNumber = ref(["已完成", "进行中", "失败"])
const remarkInputValue = ref('');
const taskCodeValue = ref('')
const editItem = ref()
const editItemIndex = ref()
const dropdownMenuList = ref<dropdownMenuList[]>(
    [
        { text: '全部时间', value: '' },
        { text: '近1周', value: '1' },
        { text: '近1个月', value: '2' },
        { text: '近3个月', value: '3'},
        { text: '近半年', value: '4' },
        { text: '近1年', value: '5' },
        { text: '近2年', value: '6' },
    ]
)
const listDataCompleted = ref<listDataCompleted[]>([
    {
        applyManId: " ",
        applyManType:  " ",
        createTime:  " ",
        delFlag:  " ",
        deptCode:  " ",
        monManCredNum:  " ",
        monManCredType:  " ",
        monManName:  " ",
        qrCodeUrl:  " ",
        reportParam:  " ",
        reportType:  " ",
        reportValidTerm:  " ",
        sex:  " ",
        shortLink:  " ",
        taskCode:  " ",
        taskId:  " ",
        taskStatus:  " ",
        tunnelCode: " ",
        detailedAuthFlag:"",
        simpleAuthFlag:"",
        remark:""
    }
])
const customName = ref<string>('')
const dateInterval = ref<string>('')
const props = defineProps(['type'])
const type = ref<any>(props.type);
//当type发生改变时，只要type不是已完成都需要修改 全部授权的状态
watch(type,(newValue) => {
    if(newValue != '1'){
        strore.checkedId = '2'
    }
})
// 替换字符
const replaceAll = (str:any, find:any, replace:any) => {
  return str.replace(new RegExp(find, 'g'), replace);
}
// 出发修改备注弹框
const getUpdateTaskRemark = (v:any,index:any)=>{
    show.value = true
    remarkInputValue.value = v.remark
    taskCodeValue.value = v.taskCode
    editItem.value = v
    editItemIndex.value = index
}
// 修改备注
const wrapperUpdateTaskRemark = () => {
    console.log(editItem.value);
    updateTaskRemark({
        remark: remarkInputValue.value,
        taskCode: JIAMIPublicData(taskCodeValue.value)
    }).then((res: any) => {
        if(res.code == 200) {
            Toast(res.msg)
            // getList()
            listDataCompleted.value[editItemIndex.value] = {...editItem.value,remark:remarkInputValue.value}
        }
        show.value = false
    })
}
// 修改备注取消
const wrapperUpdateTaskRemarkqx = () => {
    show.value = false
    remarkInputValue.value = ''
}
// 删除
const detAgainClick = (v:any) => {
    showDialog({
        message: '您确定删除吗。',
        confirmButtonText:  "好的",
        cancelButtonText:  "取消",
        showConfirmButton: true,
        showCancelButton: true,
    }).then(() => {
        deleteTask({
            taskCode: JIAMIPublicData(v.taskCode)
        }).then((res: any) => {
            if(res.code == 200) {
                Toast(res.msg)
                getList()
                getTskInfo()
            }
        })
    })
    .catch(() => {
        
    });
}
// 再次邀请
const inviteAgainClick = (v:any) => {
    router.push({ path: '/addingCustomersz', query: { taskCode: JIAMIPublicData(v.taskCode) as string } })
}
// 二维码
const goinviteCode = (v: any) => {
    sessionStorage.setItem('taskCode',JIAMIPublicData(v.taskCode) )
    router.push({ path: '/inviteCode', query: { expirationTime: v.reportValidTerm, longUrl: v.qrCodeUrl, shortUrl: v.shortLink ,isTask:1} })
}
// 去报告列表
const golistReports = (v: any) => {
    //当去报告列表的时候把这个值存起来，回来这个页面的时候用
    sessionStorage.setItem("StatusCheckedId",strore.checkedId)
    router.push({ path: '/listReports', query: { taskCode: JIAMIPublicData(v.taskCode)}})
    
}
// 用户列表
const getList = () => {
    let a = ''
    if(customName.value){
        a = JIAMIPublicData(customName.value)
    } else {
        a = ''
    }
    var data:ListFormdata = {
        customName: a,
        type:type.value,
        dateInterval: dateInterval.value
    }
    selMyTaskDetail(data).then((res: any) => {
        if(res.code == 200) {
            if(res.data.policyTaskVosFin){
              listDataCompleted.value =  res.data.policyTaskVosFin
              listDataCompleted?.value.map((v) => {
                    (v.createTime as string) = replaceAll((v.createTime as string), "T", " ");
                    (v.taskCode as string) = JIMIPublicData((v.taskCode as string));
                })
                strore.setCompletedStatusData(listDataCompleted?.value)
                strore.filterCompletedData()
            } else if (res.data.policyTaskVosDoing){
                listDataCompleted.value =  res.data.policyTaskVosDoing
                listDataCompleted?.value.map ((v)=>{
                  (v.createTime as string) = replaceAll((v.createTime as string), "T", " ");
                    (v.taskCode as string) = JIMIPublicData((v.taskCode as string));
                })
            } else if (res.data.policyTaskVosFail){
                listDataCompleted.value =  res.data.policyTaskVosFail
                listDataCompleted?.value.map ((v)=>{
                  (v.createTime as string) = replaceAll((v.createTime as string), "T", " ");
                    (v.taskCode as string) = JIMIPublicData((v.taskCode as string));
                })
            } 
        }else{
            //请求出错    数据清空
            strore.setCompletedStatusData([])
            strore.filterCompletedData()
        }
        finished.value = true;
        loading.value = false;  
    })
}
const active = ref(0);
active.value = (type.value as any) - 1
const onClickTab = ({ name }) => {
    type.value = name+1
    getList()
}
const loading = ref(false);
const finished = ref(false);

  // 任务统计
const getTskInfo = () => {
    taskInfo({}).then((res: any) => {
        if(res.code == 200) {
              arrNumber.value[0] = `已完成(${res.data.finishTaskCount})`;
              arrNumber.value[1] = `进行中(${res.data.doingTaskCount})`;
              arrNumber.value[2] = `失败(${res.data.failTaskCount})`;
        }
    })
}

onMounted(async () => {
    //如果StatusCheckedId 不为空，说明是从报告列表返回的，根据需求的要求，从报告列表返回的数据
    // 如果不是从报告列表回来的，全部为全部 （只会从已成功进报告列表）
    console.log(sessionStorage.getItem('StatusCheckedId'));
    if(!sessionStorage.getItem('StatusCheckedId')){
        strore.checkedId = '2'
        // 清理数据
        sessionStorage.removeItem("StatusCheckedId")
    }else{
        strore.checkedId = sessionStorage.getItem('StatusCheckedId')
         // 清理数据
         sessionStorage.removeItem("StatusCheckedId")
    }
    
    
//   getList()
//   getTskInfo()
});
onBeforeUnmount(() => {
    //当组件销毁时，默认该值重置为全部授权
    strore.checkedId = '2'
})
watchEffect(() => {
    type.value = props.type;
    getList()
    getTskInfo()
});
const goreports = () => {
    router.push({ path: '/listReports'})
}

const onSearch = () => {
    if(customName.value  || dateInterval.value) {
        router.push({ path: '/taskseach',query: { customName: customName.value, dateInterval: dateInterval.value }})
    }
    // getList()
};

const onFocus = (val: any) => {
    // router.push({ path: '/taskseach'})
};

const onCancel = (val: any) => {

};
</script>

<!-- less嵌套设置 -->
<style lang="less" scoped>
textarea {
            width: calc( 100% - 40px); /* 宽度可以根据需要调整 */
            padding: 10px; /* 内边距 */
            margin: 20px;
            margin-bottom: 0px;
            border-radius: 4px;
            box-sizing: border-box; /* 包括内边距和边框在内的总宽度 */
        }
.wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    .wrapperChild {
        width: 300px;
        // height: 170px;
        height: auto;
        border-radius: 10px;
        background: #F5F7FA;
        display: flex;
        align-items: center;
        justify-content: center;
        .wrapperChildDiv {
            width: 100%;
            .labelsInput {
                width: 70%;
                height: 30px;
                font-size: 13px;
                margin-top: 30px;
            }
            .wrapperChildBottom {
                width: 100%;
                display: flex;
                margin-top: 20px;
                align-items: center;
                justify-content: center;
                margin-bottom: 20px;
                div {
                    font-size: 13px;
                    color: #F5F7FA;
                    padding: 7px 30px;
                    border-radius: 3px;
                    background: #2B8AE9;
                }
                div:nth-child(1){
                    margin-left: 10px;
                }
                div:last-child{
                    margin-left: 30px;
                }
            }
        }
    }
}
.pagePad {
    width: 100%;
    height: 100%;
    .content {
        height: 100%;
        width: 100%;
        overflow: hidden;
        box-sizing: border-box;
        .contentTop {
            width: 100%;
            background-color: #FFFFFF;
            .input {
                width: 100%;
                display: flex;
                padding: 10px;
                align-items: center;
                box-sizing: border-box;
                .searchButton {
                    font-size: 15px;
                    color: #198AFA;
                    margin-left: 7px;
                }
                .searchView {
                    width: 47%;
                    border-radius: 5px;
                    border: 1px solid rgba(255, 255, 255 );
                    height: 30px;
                    background-color: #F8F9FA;
                    color: white;
                    :deep(.van-search) {
                        padding: 0px;
                        color: #333333;
                    }
                    :deep(.van-field__control){
                        color:#333333
                    }

                    :deep(.van-icon-search:before) {
                        color: #333333;
                    }
                    :deep(#van-search-1-input) {
                        font-size: 14px;
                    }
                    :deep(.van-search__content) {
                        top: -5px;
                        height: 23px;
                        color: #333333;
                        padding-left: 0;
                        position: relative;
                        background-color: transparent;
                    }
                }

                .dropdownMenu {
                    width: 37%;
                    height: 30px;
                    padding-left: 10px;
                    border-radius: 10px;
                    :deep(.van-dropdown-menu){
                        position: relative;
                    }
                    :deep(.van-dropdown-menu__bar){
                        z-index: 1;
                        position: relative;
                    }
                    
                    :deep(.van-ellipsis) {
                        color: #333333;
                    }
                    :deep(.van-dropdown-menu__bar) {
                        height: 30px;
                        border-radius: 5px;
                        background-color: #F8F9FA;
                        border: 1px solid rgba(255, 255, 255 );
                    }
                }

            }
            .tabs {
                width: 100%;
                :deep(.van-tab) {
                    background-color: #3296FA;
                    color: white;
                }
                :deep(.van-tab--active) {
                    color: white;
                }
            }
        }


        .listView {
            width: 100%;
            overflow-y: scroll;
            border-radius: 10px;
            box-sizing: border-box;
            height: calc(100% - 43px);
            background-color: #F5F7FA;
            .vanList {
                :deep(.van-cell:after) {
                    border: none;
                }
                .cells {
                    width: 100%;
                    margin-top: 10px;
                    border-radius: 7px;
                    .card {
                        width: 100%;
                        display: flex;
                        text-align: left;
                        background-color: white;
                        .cardLine {
                            width:1px; 
                            margin-top: 7px; 
                            margin-bottom: 7px; 
                            background-color: #198AFA; 
                            border-radius: 10px 0px 0px 10px; 
                        }
                        .cardT {
                            width: 90%;
                            margin-top: 10px;
                            border-radius: 7px;
                            padding-left: 13px;
                            margin-bottom: 17px;
                        }
                        .cardTTwo {
                            width: 90%;
                            margin-top: 10px;
                            border-radius: 7px;
                            padding-left: 13px;
                            margin-bottom: 17px;
                        }
                        .cardTT{
                            width: 90%;
                            margin-top: 10px;
                            border-radius: 7px;
                            padding-left: 13px;
                            margin-bottom: 17px;
                        }
                        .firstdiv{
                            opacity: 1;
                            font-size: 14px!important;
                            font-weight: bold!important;
                            color: rgba(0, 0, 0, 1)!important;
                            margin-left:-10px;
                            .fontone{
                                    font-size: 18;
                                }
                        }
                        .labels1{
                            opacity: 1;
                            font-size: 14px!important;
                            font-weight: bold!important;
                            color: rgba(0, 0, 0, 1)!important;
                        }
                        .labels {
                            display: flex;
                            font-size: 12px;
                            color: #868686;
                            padding-top: 7px;
                            div {
                                width: 70px;
                                text-align: right;
                            }
                            .labelsInput {
                                margin-left: 3px;
                                background: transparent;
                                width: calc(100% - 70px);
                            }
                            input[disabled],
                            input:disabled,
                            input.disabled {
                            color: #222;
                            opacity: 1;
                            -webkit-text-fill-color: #222;
                            -webkit-opacity: 1;
                            }
                            .textContent {
                                font-weight: 500;
                                margin-left: 10px;
                                font-size: 12px!important;
                                color: rgba(34, 34, 34, 1);
                            }
                        }
                        .labelsButt {
                            width: 97%;
                            justify-content: end;
                            .labelsButton {
                                display: block;
                                color: #F5F7FA;
                                margin-left: 10px;
                                padding: 7px 13px;
                                border-radius: 3px;
                                background: #3296FA;
                            } 
                        }
                    }
                }
            }



        }

    }
}
:deep(.van-radio__label) {
    font-size: 12px !important;
}  
:deep(.van-radio__icon .van-icon){
    font-size: 12px;
    line-height: 14px;
}
</style>


<!-- 

    1、任务统计页面展示的是该从业人员发起的所有有效保单检视任务数据。包括通过h5页面发起和接口发起两个形式创建的检视任务。按已完成、进行中、失败三个维度展示任务数据。已完成的任务不展示任务流程节点，进行中和失败的任务展示任务流程节点。
    2、任务流程节点即任务状态，进行中的任务状态包括已创建、已查看告知页、已授权认证、已确认保单范围、生成报告中状态的任务。
    失败维度包括：未查看告知页、未授权/身份认证、未选择保单范围、无有效保单、报告生成失败状态的任务。失败维度中的未查看告知页、未授权/身份认证、未选择保单范围三种状态是指，在邀请二维码/链接超过7天有效期后，任务还停留在以上三种状态，则计为任务失败。终止状态是指在后台进行终止操作的任务状态 。
    3、任务统计列表按邀请时间倒序排列。每页展示20个任务，通过上滑加载的方式加载20个数据。
    4、搜索：根据客户姓名搜索任务，精确查询，点击“搜索”后，展示查询到的任务，如未查询到任务，页面提示：根据输入的关键字，未查询到任务信息。
    5、任务邀请时间即任务链接生成时间。
    6、按邀请时间下拉选项查询时，查询结果列表按邀请时间倒序排列。
    任务编号生成规则：保单登记机构编码6位+长日期（yymmddHHMMSS年月日时分秒12）+4位流水号.
 -->
